package com.ibeeking.found.id.rest.service.impl;


import com.ibeeking.found.id.rest.service.SerialNumberService;
import com.ibeeking.found.id.service.common.utils.RedisUtil;
import com.ibeeking.found.id.service.common.utils.StringUtil;
import com.ibeeking.found.id.service.common.utils.TimeUtil;
import com.alibaba.nacos.shaded.com.google.protobuf.ServiceException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @ClassName: SerialNumberServiceImpl
 * @Author ibeeking
 * @Description:
 * @Date: 2022/2/16 17:57
 * @Version: 1.0
 */
@Service
public class SerialNumberServiceImpl implements SerialNumberService {

    @Resource
    private RedisUtil redisUtil;


    //生成带日期点编号
    @Override
    public String generateNumberWithDate(String Type,String bizCode,int numberSize) throws ServiceException {
        /** 检查业务码 */
        boolean isLegal = isLegal(bizCode);
        if (!isLegal) {
            throw new ServiceException("bizCode参数不合法");
        }
        /** 获取今天的日期:yyyyMMdd */
        String date = TimeUtil.getToday();
        /** 构造redis的key */
        String key = Type + date;
        /** 自增 */
        long sequence = redisUtil.incr(key,1);
        String seq = StringUtil.getSequence(sequence,numberSize - date.length());
        StringBuilder sb = new StringBuilder();
        sb.append(date).append(bizCode).append(seq);
        String serial = sb.toString();
        return serial;
    }

    @Override
    public String generateNumberWithDate(String Type,int numberSize) throws ServiceException {
        /** 获取今天的日期:yyyyMMdd */
        String date = TimeUtil.getToday();
        /** 构造redis的key */
        String key = Type + date;
        /** 自增 */
        long sequence = redisUtil.incr(key,1);
        String seq = StringUtil.getSequence(sequence,numberSize - date.length());
        StringBuilder sb = new StringBuilder();
        sb.append(date).append(seq);
        String serial = sb.toString();
        return serial;
    }

    @Override
    public String generateNumber(String Type, int numberSize) throws ServiceException {

        /** 构造redis的key */
        String key = Type;
        /** 自增 */
        long sequence = redisUtil.incr(key,1);
        String seq = StringUtil.getSequence(sequence,numberSize);
        StringBuilder sb = new StringBuilder();
        sb.append(seq);
        String serial = sb.toString();
        return serial;
    }
}
